/**
 * 二次缓动函数
 */
function easeInOutQuad(t: number, b: number, c: number, d: number): number {
  t /= d / 2
  if (t < 1) return (c / 2) * t * t + b
  t--
  return (-c / 2) * (t * (t - 2) - 1) + b
}

/**
 * 获取当前滚动位置
 */
function getScrollTop(): number {
  return (
    window.pageYOffset ||
    document.documentElement.scrollTop ||
    document.body.scrollTop ||
    0
  )
}

/**
 * 设置滚动位置
 */
function setScrollTop(value: number) {
  document.documentElement.scrollTop = value
  document.body.scrollTop = value
}

/**
 * 平滑滚动到指定位置
 * @param to 目标位置
 * @param duration 动画时长（毫秒），默认 500
 * @returns Promise<void>
 */
export function scrollTo(to: number, duration = 500): Promise<void> {
  return new Promise((resolve) => {
    const start = getScrollTop()
    const change = to - start
    const increment = 20
    let currentTime = 0

    function animateScroll() {
      currentTime += increment
      const val = easeInOutQuad(currentTime, start, change, duration)
      setScrollTop(val)
      if (currentTime < duration) {
        window.requestAnimationFrame(animateScroll)
      } else {
        setScrollTop(to)
        resolve()
      }
    }

    animateScroll()
  })
}